package com.luyuan.crm.sale.web;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.luyuan.crm.formula.model.Formula;
import com.luyuan.crm.formula.model.Inventory;
import com.luyuan.crm.product.model.ProductType;
import com.luyuan.crm.question.model.Question;
import com.luyuan.crm.question.model.QuestionExtend;
import com.luyuan.crm.question.model.QuestionExtendField;
import com.luyuan.crm.question.model.QuestionValue;
import com.luyuan.crm.question.service.QuestionExtendService;
import com.luyuan.crm.question.service.QuestionValueService;
import com.luyuan.crm.sale.model.FormulaOrder;
import com.luyuan.crm.sale.model.OrderType;
import com.luyuan.crm.sale.model.ProductOrder;

@Component("orderWizardAction")
@Scope("wizard")
public class OrderWizardAction extends BaseOrderWizardAction {
    @Resource(name = "questionExtendService")
    private QuestionExtendService questionExtendService;

    @Resource(name = "questionValueService")
    private QuestionValueService questionValueService;

    private ProductType productType;

    private Formula formula = new Formula();

    private FormulaOrder formulaOrder = new FormulaOrder();

    private Question question;

    private List<QuestionValue> questionExtendValues;

    private Map<QuestionExtend, List<QuestionExtendField>> questionExtendMap = new LinkedHashMap<QuestionExtend, List<QuestionExtendField>>();

    @Override
    public void saveProduct() {
        order.setFormulaOrder(formulaOrder);
        formulaOrder.setOrder(order);

        super.saveProduct();

        saveExtendValue();
    }

    @Override
    public void updateProduct() {
        order.setFormulaOrder(formulaOrder);
        formulaOrder.setOrder(order);

        super.updateProduct();

        updateExtendValue();
    }

    private void saveExtendValue() {
        Set<QuestionExtend> questionExtends = questionExtendMap.keySet();
        for (QuestionExtend questionExtend : questionExtends) {
            QuestionValue questionExtendValue = new QuestionValue();
            questionExtendValue.setExtendValue(questionExtend.getDefaultValue());
            questionExtend.setDefaultValue("");
            questionExtendValue.setCustomer(customer);
            questionExtendValue.setQuestion(question);
            questionExtendValue.setQuestionExtend(questionExtend);

            questionValueService.saveQuestionValue(questionExtendValue);
        }
    }

    private void updateExtendValue() {
        Set<QuestionExtend> questionExtends = questionExtendMap.keySet();
        for (QuestionExtend questionExtend : questionExtends) {
            // QuestionExtendValue questionExtendValue = new
            // QuestionExtendValue();
            for (QuestionValue questionExtendValue : questionExtendValues) {
                if (questionExtendValue.getQuestionExtend().getId().equals(questionExtend.getId())) {
                    questionExtendValue.setExtendValue(questionExtend.getDefaultValue());
                    questionExtend.setDefaultValue("");
                    questionExtendValue.setCustomer(customer);
                    questionExtendValue.setQuestion(question);
                    questionExtendValue.setQuestionExtend(questionExtend);

                    questionValueService.updateQuestionValue(questionExtendValue);
                    questionExtendService.updateQuestionExtend(questionExtend);
                }
            }

        }
    }

    public void loadQuestion() {
        if (productType == null) {
            return;
        }

        question = productType.getQuestion();

        // 如果没有关联调查表直接跳转到清单产品步骤
        if (question == null) {
            // return wizardAccessor
            // .gotoStep("luyuan_crm_sale_choose_formula_product");
            return;
        }
        // 获取扩展项
        Set<QuestionExtend> exts = question.getQuestionExtends();
        for (QuestionExtend questionExtend : exts) {
            questionExtendService.refresh(questionExtend);
            // 获取扩展项的子项
            Set<QuestionExtendField> efoSet = questionExtend.getQuestionExtendFields();
            List<QuestionExtendField> subItems = new ArrayList<QuestionExtendField>();
            for (QuestionExtendField questionExtendField : efoSet) {
                subItems.add(questionExtendField);
            }

            questionExtendMap.put(questionExtend, subItems);
        }

        questionExtendMap = loadQestionDefaultValue(questionExtendMap);
        // return wizardAccessor.nextStep();
    }

    private Map<QuestionExtend, List<QuestionExtendField>> loadQestionDefaultValue(
            Map<QuestionExtend, List<QuestionExtendField>> qeMap) {
        if (customer.getId() == null) {
            return qeMap;
        }

        questionExtendValues = questionValueService.findByCustomer(customer, productType.getQuestion());

        Set<QuestionExtend> qe = qeMap.keySet();
        for (QuestionExtend q : qe) {
            int len = questionExtendValues.size();
            for (int i = 0; i < len; i++) {

                if (questionExtendValues.get(i).getQuestionExtend().getId().equals(q.getId())) {
                    q.setDefaultValue(questionExtendValues.get(i).getExtendValue());
                }
            }

        }

        return qeMap;
    }

    /**
     * 加载清单
     */
    private void loadFormulaProduct() {
        if (formula == null || formula.getId() == null) {
            return;
        }
        products = new ArrayList<ProductOrder>();
        Set<Inventory> inventories = formula.getInventorys();

        for (Inventory inventory : inventories) {
            ProductOrder productOrder = new ProductOrder();
            productOrder.setProduct(inventory.getProduct());
            productOrder.setName(inventory.getProduct().getName());
            productOrder.setSpecification(inventory.getProduct().getSpecification());
            productOrder.setCount(inventory.getQuantity());
            productOrder.setGift(inventory.isGift());
            productOrder.setPrice(inventory.getProduct().getPrice());
            productOrder.setSubTotal(inventory.getQuantity() * inventory.getProduct().getPrice());

            products.add(productOrder);
        }
    }

    public void loadFormulaInfo() {
        if (formula == null || formula.getId() == null) {
            formulaOrder = new FormulaOrder();
            products = new ArrayList<ProductOrder>();
            return;
        }

        formulaOrder.setDays(formula.getDays());
        formulaOrder.setBeforeBreakfast(formula.getBeforeBreakfast());
        formulaOrder.setAfterBreakfast(formula.getAfterBreakfast());
        formulaOrder.setBeforeDinner(formula.getBeforeDinner());
        formulaOrder.setAfterDinner(formula.getAfterDinner());
        formulaOrder.setBeforeLunch(formula.getBeforeLunch());
        formulaOrder.setAfterLunch(formula.getAfterLunch());
        formulaOrder.setBeforeSleep(formula.getBeforeSleep());
        formulaOrder.setCustomerRequire(formula.getCustomerRequire());
        formulaOrder.setLifeNote(formula.getLifeNote());
        formulaOrder.setName(formula.getName());
        formulaOrder.setNote(formula.getNote());
        formulaOrder.setOldDrugBill(formula.getOldDrugBill());
        formulaOrder.setPrice(formula.getPrice());
        formulaOrder.setPurpose(formula.getPurpose());
        formulaOrder.setRemarks(formula.getRemarks());
        formulaOrder.setSpecialPrice(formula.getSpecialPrice());
        formulaOrder.setProductType(productType);
        formulaOrder.setFormula(formula);

        loadFormulaProduct();
    }

    public DataModel getChoseTableModel() {
        return new ListDataModel(products);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        super.afterPropertiesSet();

        order.setOrderType(OrderType.FORMULA);
        productType = (ProductType) getRequestAttribute("productType");

        setRequestAttribute("productType", productType, true);
        if (order.getId() != null) {
            productType = order.getFormulaOrder().getProductType();
            formulaOrder = order.getFormulaOrder();
            formula = formulaOrder.getFormula();
            if (formula != null) {
                formula.getName();
            }
        }

        loadQuestion();
    }

    @Override
    public void onCustomerChange() {
        super.onCustomerChange();

        questionExtendMap = loadQestionDefaultValue(questionExtendMap);
    }

    public Formula getFormula() {
        return formula;
    }

    public void setFormula(Formula formula) {
        this.formula = formula;
    }

    public Question getQuestion() {
        return question;
    }

    public void setQuestion(Question question) {
        this.question = question;
    }

    public Map<QuestionExtend, List<QuestionExtendField>> getQuestionExtendMap() {
        return questionExtendMap;
    }

    public void setQuestionExtendMap(Map<QuestionExtend, List<QuestionExtendField>> questionExtendMap) {
        this.questionExtendMap = questionExtendMap;
    }

    public FormulaOrder getFormulaOrder() {
        return formulaOrder;
    }

    public void setFormulaOrder(FormulaOrder formulaOrder) {
        this.formulaOrder = formulaOrder;
    }

    public ProductType getProductType() {
        return productType;
    }

    public List<QuestionValue> getQuestionExtendValues() {
        return questionExtendValues;
    }

    public void setQuestionExtendValues(List<QuestionValue> questionExtendValues) {
        this.questionExtendValues = questionExtendValues;
    }
}
